package com.seminario.spring.manager;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.seminario.spring.domain.Muro;
import com.seminario.spring.domain.Perfil;
import com.seminario.spring.domain.Usuario;
import com.seminario.spring.form.RegistrationForm;
import com.seminario.spring.service.CaraLibroService;
import com.seminario.spring.service.UserService;

@Service
public class UserManagerImpl implements UserManager{
	
	@Autowired
	private UserService userService;
	@Autowired
	private CaraLibroService caraLibroService;
	
	@Override
	@Transactional
	public void saveUser(RegistrationForm registerForm) throws Exception {
		boolean emailExsist = userService.getUser(registerForm.getEmail())!=null?true:false;
		if(emailExsist){
			throw new Exception();
		}
		
		Usuario u = new Usuario();
		u.setEmail(registerForm.getEmail());
		u.setFirstname(registerForm.getFirstname());
		u.setLastname(registerForm.getLastname());
		u.setPassword(registerForm.getPassword());
		Perfil p = new Perfil();
		p.setUser(u);
		u.setPerfil(p);
		p = userService.saveUser(p);
		Muro m = new Muro();
		m.setPerfil(p);
		caraLibroService.guardarMuro(m);
		
		
		
	}

	@Override
	@Transactional
	public boolean validateUser(String email, String password, HttpSession session) {
		Usuario validateUser = userService.validateUser(email, password);
		if(validateUser==null){
			session.setAttribute("loggedUser", null);
			return false;
		}else{
			session.setAttribute("loggedUser", validateUser.getPerfil());
			return true;
		}
	}
}
